require 'cgi'

module Oos4ruby
class Search
  
=begin rdoc
  Method to search services/places into 11870. Returns a Sites collection
  available parameters:
  <tt>q</tt>:: string that represents a siple query.
  <tt>bbox</tt>:: array of points that delimiters a rectangle, SW and NE.
  <tt>as</tt>:: area specified by a slug. I.E: /es/madrid.
  <tt>tags</tt>:: array of tags.
  <tt>tag_op</tt>:: tags operator, "and" or "or".
  <tt>lat</tt>:: latitude of the center point of an area.
  <tt>lon</tt>:: longitude of the center point of an area.
  <tt>radius</tt>:: radius to create a rectangle from the center point of an area.
  <tt>page</tt>:: page number in the search results
=end
  def Search.find(auth, opts)
    query = "#{SEARCH_URL}?#{parse_params(opts)}"
    
    getter = HTTPInvoker.new query, auth
    
    worked = getter.get
    raise RuntimeError.new(getter.response.message) unless worked
    Sites.new(Feed.read(getter.body), auth, nil)
  end
  
  def Search.parse_params(args)
    raise "at least a parameter is mandatory" if args.nil? || args.empty?

    args[:q] = CGI.escape(args[:q]) if args.include?(:q)
    args[:bbox] = args[:bbox].join(",") if args.include?(:bbox)
    args[:tag] = args.delete(:tags).map {|tag| CGI.escape(tag)} if args.include?(:tags)
    args[:tagOp] = args.delete(:tag_op) if args.include?(:tag_op)     

    args.map do |k, v|
      if v.respond_to?(:each_with_index)
        v.map {|m| "#{k}=#{m}"}
      else
        "#{k}=#{v}"
      end
    end.flatten.join("&")
  end
end
end


